/*
 * Copyright (c) 2020-2022 Jinsp-tech. All rights reserved.
 */

package com.jinsp.networklibrary;

import android.util.Log;

import com.jinsp.networklibrary.bean.TCPBaseDataBean;
import com.jinsp.networklibrary.command.TCPCommandData;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.keepalive.KeepAliveMessageFactory;

/**
 * Created by luoshuai on 1/13/22
 * <p>
 * 心跳监听
 */
public class TCPHearBeatFactory implements KeepAliveMessageFactory {

    private final String TAG = "TCPHearBeatFactory";
    private final TCPBaseDataBean<String> heartBeatRequestDataBean;      //心跳请求数据

    public TCPHearBeatFactory(int heartBeatCommandNumber, int clientState) {
        heartBeatRequestDataBean = new TCPBaseDataBean<>();
        heartBeatRequestDataBean.setState(clientState);
        heartBeatRequestDataBean.setCommandNumber(heartBeatCommandNumber);
    }

    @Override
    public boolean isRequest(IoSession session, Object message) {
        return false;
    }

    @Override
    public boolean isResponse(IoSession session, Object message) {
        if (message instanceof TCPBaseDataBean) {
            TCPBaseDataBean<?> tcpBaseDataBean = (TCPBaseDataBean<?>) message;
            if (tcpBaseDataBean.getCommandNumber() == 100) {
                Log.d(TAG, "客户端收到心跳回应");
                return true;
            }
        } else if (message instanceof TCPCommandData) {
            TCPCommandData hearBeatCommandData = (TCPCommandData) message;
            return hearBeatCommandData.getCommandNumber() == 100;
        }
        return false;
    }

    @Override
    public Object getRequest(IoSession session) {
        Log.d(TAG, "客户端发送心跳请求");
        return heartBeatRequestDataBean;
    }

    @Override
    public Object getResponse(IoSession session, Object request) {
        return null;
    }
}
